package com.glidebitmappool.internal;

import java.util.Queue;

/**
 * 位图密钥池基类
 *
 * @author renpengfei
 * @param <T>
 * @since 2021-03-12
 */
abstract class BaseKeyPool<T extends Poolable> {
    /**
     * 默认最大容量
     */
    private static final int MAX_SIZE = 20;
    private final Queue<T> keyPool = Util.createQueue(MAX_SIZE);

    /**
     * 通过轮询从位图密钥池获取
     *
     * @return T
     */
    protected T get() {
        T result = keyPool.poll();
        if (result == null) {
            result = create();
        }
        return result;
    }

    /**
     * 将指定元素插入密钥池
     *
     * @param key
     */
    public void offer(T key) {
        if (keyPool.size() < MAX_SIZE) {
            keyPool.offer(key);
        }
    }

    /**
     * 初始化
     *
     * @return T
     */
    protected abstract T create();
}

